﻿
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using RapidProject.Pages.Ultrasound;
using Service.DI;
using Service.Server.Log;
using Service.Server.Ultrasound;
using System.IO;
using System.Reflection;
using System.Windows;
using Utils.App;
using ViewModel;
using ViewModel.Ultrasound;

namespace RapidProject
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private readonly IHost _host;

        public App()
        {
            //初始化log4net
            InitializeLog4Net();

            _host = Host.CreateDefaultBuilder()
                .ConfigureServices((context, services) =>
                {
                    ConfigureServices(services);
                }).Build();
        }

        private void InitializeLog4Net()
        {
            //获取当前目录 Assembly.GetEntryAssembly()
            Appdir.AppRoot = Environment.CurrentDirectory;

            // 配置log4net
            var logRepository = log4net.LogManager.GetRepository(Assembly.GetEntryAssembly());
            log4net.Config.XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));

            // 记录启动日志
            var logger = log4net.LogManager.GetLogger(typeof(App));
            logger.Info("======= 应用程序启动 =======");
        }

        protected override async void OnStartup(StartupEventArgs e)
        {
            await _host.StartAsync(); // 启动Host

            // 获取Logger记录启动过程
            var logger = _host.Services.GetRequiredService<ILogServer<App>>();
            logger.LogInfo("应用程序启动中...");

            // 从容器中获取主窗口并显示
            var mainWindow = _host.Services.GetRequiredService<MainWindow>();
            mainWindow.Show();

            base.OnStartup(e);
        }

        protected override async void OnExit(ExitEventArgs e)
        {
            var logger = _host.Services.GetRequiredService<ILogServer<App>>();
            logger.LogInfo("应用程序退出");

            using (_host)
            {
                await _host.StopAsync(TimeSpan.FromSeconds(5));
            }
            base.OnExit(e);
        }

        private void ConfigureServices(IServiceCollection services)
        {

            #region 手动注册

            //// 1. 注册工具类（日志，中间件等）
            //services.AddSingleton(typeof(ILogServer<>), typeof(LogServer<>));//（泛型注册）
            ////services.AddSingleton<ILogger, FileLogger>();

            //// 2. 注册Model层（如果有需要）
            //// services.AddScoped<IModelRepository, ModelRepository>();

            //// 3. 注册Service层
            //services.AddTransient<IUltrasoundServer, UltrasoundServer>();

            //// 4. 注册ViewModel层
            //services.AddSingleton<MainWindowViewModel>();
            //services.AddSingleton<UltrasoundViewModel>();

            //// 5,注册页面  容器会自动解析构造函数依赖
            //services.AddSingleton<UltrasoundView>();
            //services.AddSingleton<MainWindow>();

            #endregion

            #region 自动注册

            // 1. 注册工具类（日志，中间件等）
            services.AddSingleton(typeof(ILogServer<>), typeof(LogServer<>));//（泛型注册）
                                                                             //services.AddSingleton<ILogger, FileLogger>();

            // 2. 注册Model层（如果有需要）
            // services.AddScoped<IModelRepository, ModelRepository>();

            //注册瞬时
            //注册作用域
            //注册单例
            services.AutoRegisterServices();
            #endregion



        }

    }

}
